﻿#region Author

//// Yevhen Bobrov, http://blog.xtalion.com 

#endregion

using System;
using System.Threading;

namespace Silverlight.Core.Infrastructure.Actions
{
	public static class Parallel
	{
		public static IAction Actions(params IAction[] actions)
		{
			return new ParallelAction(actions);
		}

		private class ParallelAction : IAction
		{
			public event EventHandler Completed;

			readonly IAction[] _actions;
			int _remaining;

			public ParallelAction(IAction[] actions)
			{
				_actions = actions;
			}

			public void Execute()
			{
				_remaining = _actions.Length;

				foreach (IAction action in _actions)
				{
					action.Completed += delegate
					{
						if (Interlocked.Decrement(ref _remaining) == 0)
							SignalCompleted();
					};

					action.Execute();
				}
			}

			void SignalCompleted()
			{
				EventHandler handler = Completed;

				if (handler != null)
					Call.OnUIThread(() => handler(this, EventArgs.Empty));
			}
		}
	}
}
